package com.kfm.servlet;

import com.kfm.model.FileDO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet("/download")
public class DownloadServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("utf-8");

        String key = req.getParameter("key");

        FileDO fileDO = UploadServlet.map.get(key);

        if (fileDO != null){
            File file = new File(fileDO.getPath());

            FileInputStream fis = new FileInputStream(file);

            //Content‐Disposition 设置要被下载的文件名
            resp.setHeader("Content-Disposition", "attachment;filename=" + fileDO.getName());

            fis.transferTo(resp.getOutputStream());

            fis.close();
        }else{
            resp.sendError(404, key + " 资源不存在");
        }
    }
}
